import React, { useState, useEffect, useRef } from 'react';
import {
  Modal,
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Animated,
  Dimensions,
  PermissionsAndroid,
  Platform,
  ActivityIndicator,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import voiceService from '../services/voiceService';
import { analyzeIntent, getWelcomePrompt } from '../utils/voiceKeywords';
import { COLORS } from '../styles/constants';

const { width } = Dimensions.get('window');

const VoiceGuideModalBaidu = ({ visible, onClose, scenicArea }) => {
  const [status, setStatus] = useState('asking'); // asking, listening, speaking, recognizing, completed, error
  const [recognizedText, setRecognizedText] = useState('');
  const [errorMessage, setErrorMessage] = useState('');

  const pulseAnim = useRef(new Animated.Value(1)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;

  // 当前弹窗是否仍然有效（用于在关闭后阻止后续异步回调继续执行）
  const isActiveRef = useRef(false);

  // 请求麦克风权限
  const requestMicrophonePermission = async () => {
    if (Platform.OS === 'ios') {
      return true; // iOS 权限在 Info.plist 中配置
    }

    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
        {
          title: '麦克风权限',
          message: '需要使用麦克风进行语音识别和语音交互',
          buttonPositive: '允许',
          buttonNegative: '拒绝',
        },
      );
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (error) {
      return false;
    }
  };

  // 初始化语音导览
  const initializeGuide = async () => {
    if (!isActiveRef.current) return;

    try {
      setStatus('asking');

      // 请求麦克风权限
      const hasPermission = await requestMicrophonePermission();
      if (!isActiveRef.current) return;
      if (!hasPermission) {
        // 用户拒绝权限，直接关闭弹窗，不播报任何内容
        onClose();
        return;
      }

      // 🔊 播放欢迎提示（使用本地 TTS）
      const welcomeText = getWelcomePrompt(
        scenicArea?.areaName || scenicArea?.name,
      );
      if (!isActiveRef.current) return;

      setStatus('speaking');
      await voiceService.speak(welcomeText);
      if (!isActiveRef.current) return;

      // ⏳ 等待 500ms，让音频系统完全切换完成
      await new Promise(resolve => setTimeout(resolve, 500));
      if (!isActiveRef.current) return;

      // 开始监听用户回答
      startListening();
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('语音服务初始化失败：' + (error.message || '未知错误'));
      setStatus('error');
    }
  };

  // 开始监听用户语音
  const startListening = async () => {
    if (!isActiveRef.current) return;

    try {
      setStatus('listening');
      setRecognizedText('');

      await voiceService.startListening({
        onStart: () => {
          if (!isActiveRef.current) return;
        },
        onResults: (text, { isFinal } = { isFinal: false }) => {
          if (!isActiveRef.current) return;
          if (!text || !text.trim()) {
            return;
          }
          if (isFinal) {
            handleRecognitionResult(text);
          } else {
            setRecognizedText(text);
          }
        },
        onError: error => {
          if (!isActiveRef.current) return;
          setErrorMessage(error.message || '讯飞语音识别失败');
          setStatus('error');
        },
        onEnd: () => {
          // 结束事件在关闭后触发时直接忽略
        },
      });
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('启动录音失败：' + error.message);
      setStatus('error');
    }
  };

  // 处理识别结果
  const handleRecognitionResult = async text => {
    if (!isActiveRef.current) return;

    try {
      await voiceService.stopListening();
      if (!isActiveRef.current) return;
      setStatus('recognizing');
      setRecognizedText(text);

      // 检查关键词
      const result = analyzeIntent(text);

      if (result.intent === 'positive') {
        // 用户想听讲解
        await playGuideContent();
      } else if (result.intent === 'negative') {
        // 用户不想听，立即关闭弹窗
        await cleanup();
        onClose();
      } else {
        // 无法判断，重新询问
        setErrorMessage('未识别到明确回答，请再说一遍');
        setTimeout(() => {
          if (!isActiveRef.current) return;
          setErrorMessage('');
          startListening();
        }, 2000);
      }
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('处理失败：' + error.message);
      setStatus('error');
    }
  };

  // 播放景区讲解
  const playGuideContent = async () => {
    if (!isActiveRef.current) return;

    try {
      setStatus('speaking');
      const content =
        scenicArea?.introduction ||
        scenicArea?.description ||
        '暂无景区介绍信息';
      await voiceService.speak(content);
      if (!isActiveRef.current) return;
      setStatus('completed');
      setTimeout(() => {
        if (!isActiveRef.current) return;
        onClose();
      }, 2000);
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('播放讲解失败');
      setStatus('error');
    }
  };

  // 清理资源 - 只清理 TTS，不影响音频播放
  const cleanup = async () => {
    // 标记为无效，后续异步回调直接退出
    isActiveRef.current = false;
    try {
      // 立即停止语音识别
      await voiceService.stopListening();
      // 立即停止语音播报
      await voiceService.stopSpeaking();
      // 清理TTS资源
      await voiceService.cleanupTts();
    } catch (error) {
      // 忽略清理错误
    }
  };

  // 监听弹窗显示/隐藏
  useEffect(() => {
    if (visible && scenicArea) {
      // 弹窗显示时标记为激活
      isActiveRef.current = true;
      initializeGuide();
    } else {
      // 弹窗隐藏时立即清理
      cleanup();
    }

    return () => {
      isActiveRef.current = false;
      cleanup();
    };
  }, [visible, scenicArea]);

  // 脉搏动画（录音时）
  useEffect(() => {
    if (status === 'listening') {
      Animated.loop(
        Animated.sequence([
          Animated.timing(pulseAnim, {
            toValue: 1.2,
            duration: 800,
            useNativeDriver: true,
          }),
          Animated.timing(pulseAnim, {
            toValue: 1,
            duration: 800,
            useNativeDriver: true,
          }),
        ]),
      ).start();
    } else {
      pulseAnim.setValue(1);
    }
  }, [status]);

  // 淡入动画
  useEffect(() => {
    if (visible) {
      Animated.timing(opacityAnim, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true,
      }).start();
    } else {
      opacityAnim.setValue(0);
    }
  }, [visible]);

  // 获取状态文本
  const getStatusText = () => {
    switch (status) {
      case 'asking':
        return '正在询问...';
      case 'listening':
        return '请说出您的回答';
      case 'speaking':
        return '正在播放...';
      case 'recognizing':
        return '正在识别...';
      case 'completed':
        return '完成';
      case 'error':
        return '出错了';
      default:
        return '';
    }
  };

  // 获取状态图标
  const getStatusIcon = () => {
    switch (status) {
      case 'asking':
      case 'speaking':
        return 'volume-high';
      case 'listening':
        return 'mic';
      case 'recognizing':
        return 'search';
      case 'completed':
        return 'checkmark-circle';
      case 'error':
        return 'alert-circle';
      default:
        return 'help-circle';
    }
  };

  // 获取状态颜色
  const getStatusColor = () => {
    switch (status) {
      case 'error':
        return COLORS.status.error;
      case 'completed':
        return COLORS.status.success;
      case 'listening':
        return COLORS.primary;
      default:
        return COLORS.status.info;
    }
  };

  return (
    <Modal
      visible={visible}
      transparent
      animationType="fade"
      onRequestClose={onClose}
    >
      <Animated.View style={[styles.container, { opacity: opacityAnim }]}>
        <View style={styles.backdrop}>
          <View style={styles.content}>
            {/* 状态图标 */}
            <Animated.View
              style={[
                styles.iconContainer,
                {
                  backgroundColor: getStatusColor(),
                  transform: [{ scale: pulseAnim }],
                },
              ]}
            >
              <Icon name={getStatusIcon()} size={60} color="#FFFFFF" />
            </Animated.View>

            {/* 状态文本 */}
            <Text style={styles.statusText}>{getStatusText()}</Text>

            {/* 识别文本 */}
            {recognizedText ? (
              <View style={styles.recognizedContainer}>
                <Text style={styles.recognizedLabel}>识别结果：</Text>
                <Text style={styles.recognizedText}>{recognizedText}</Text>
              </View>
            ) : null}

            {/* 错误信息 */}
            {errorMessage ? (
              <View style={styles.errorContainer}>
                <Icon name="alert-circle" size={20} color="#FF3B30" />
                <Text style={styles.errorText}>{errorMessage}</Text>
              </View>
            ) : null}

            {/* 加载指示器 */}
            {(status === 'asking' || status === 'recognizing') && (
              <ActivityIndicator
                size="large"
                color={getStatusColor()}
                style={styles.loader}
              />
            )}

            {/* 关闭按钮 */}
            <TouchableOpacity
              style={styles.closeButton}
              onPress={async () => {
                // 立即停止所有语音服务
                await cleanup();
                // 立即关闭弹窗
                onClose();
              }}
              activeOpacity={0.7}
            >
              <Text style={styles.closeButtonText}>关闭</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Animated.View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backdrop: {
    flex: 1,
    backgroundColor: 'rgba(15, 23, 42, 0.7)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    width: width * 0.85,
    backgroundColor: COLORS.background.card,
    borderRadius: 20,
    padding: 30,
    alignItems: 'center',
    shadowColor: COLORS.shadow,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 10,
    elevation: 5,
  },
  iconContainer: {
    width: 120,
    height: 120,
    borderRadius: 60,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 20,
  },
  statusText: {
    fontSize: 20,
    fontWeight: '600',
    color: COLORS.text.primary,
    marginBottom: 15,
  },
  recognizedContainer: {
    width: '100%',
    backgroundColor: COLORS.background.secondary,
    borderRadius: 10,
    padding: 15,
    marginTop: 10,
  },
  recognizedLabel: {
    fontSize: 14,
    color: COLORS.text.tertiary,
    marginBottom: 5,
  },
  recognizedText: {
    fontSize: 16,
    color: COLORS.text.primary,
    lineHeight: 24,
  },
  errorContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: COLORS.primaryLight,
    borderRadius: 10,
    padding: 15,
    marginTop: 10,
  },
  errorText: {
    fontSize: 14,
    color: COLORS.status.error,
    marginLeft: 10,
    flex: 1,
  },
  loader: {
    marginTop: 15,
  },
  closeButton: {
    marginTop: 20,
    paddingHorizontal: 40,
    paddingVertical: 12,
    backgroundColor: COLORS.primary,
    borderRadius: 25,
  },
  closeButtonText: {
    fontSize: 16,
    fontWeight: '600',
    color: '#FFFFFF',
  },
});

export default VoiceGuideModalBaidu;
